
$(function(){
    let _deleteIds = null, _action = '/add';
    const convertor = {type:['静态资源', '目录', '菜单', '接口']};
    const alerter = Frame2.alert.init({$div:$('#alertbar')});
    const setting = {
        callback: {
            onClick: function (event, treeId, treeNode) {
                $('#tablebar_pid').val(treeNode.id);
                $('#addModal').find("[name='pid']").val(treeNode.id)
            }
        }
    };
    const table = $('#table').bootstrapTable({
        url: _DIR + '/table',
        cache:false,
        toolbar:'#formbar',
        pagination:true,
        sidePagination : 'server',//服务器端分页 返回数据 {rows:[],total:1}
        pageNumber : 1,
        pageSize: 15,
        pageList: [15, 20, 50, 100],//分页步进值
        columns: [{checkbox: true, valign: "bottom"},
        {
            showSelectTitle:true,
            field: 'id',
            title: 'ID'
        }, {
            field: 'pid',
            title: 'PID',
        }, {
            field: 'name',
            title: '资源名',
        }, {
            field: 'url',
            title: 'URL'
        }, {
            field: 'type',
            title: '类型',
            formatter : function (value, row, index, field) {
                return convertor.type[value * 1];
            }
        }, {
           field: 'sorting',
           title: '排序(升序)'
        }, {
            field: 'shiro',
            title: '权限码'
        }, {
            title:'操作',
            align: 'center',
            class: 'action',
            formatter:function(value, row, index, field){
                let btn = '<button type="button" class="btn btn-xs btn-success view" title="点击查看资源详情">查看</button>';
                if (row.id == 1) {
                    btn += '<button type="button" class="btn btn-xs" disabled>根节点禁止修改和删除</button>';
                } else {
                    btn += '<button type="button" class="btn btn-xs btn-primary update">修改</button>'
                        +'<button type="button" class="btn btn-xs btn-danger del">删除</button>';
                }
                return btn;
            },
            events:{
                'click .view': function(e,value,row,index){
                    let view = $('#viewModal');
                    view.find("#view_pid").text(row.pid);
                    view.find("#view_type").text(convertor.type[row.type * 1])
                    view.find("#view_name").text(row.name)
                    view.find("#view_shiro").text(row.shiro)
                    view.find("#view_icon").text(row.icon)
                    view.find("#view_sorting").text(row.sorting)
                    view.find("#view_url").text(row.url)
                    view.find('#view_createTime').text(new Date(row.createTime).Format('yyyy年MM月dd日 hh:mm:ss'));
                    view.find('#view_updateTime').text(new Date(row.updateTime).Format('yyyy年MM月dd日 hh:mm:ss'));
                    view.find("#view_description").text(row.description)
                    //form.find("[name='date']").text(row.date)
                    view.modal('show');
                },
                'click .update': function(e,value,row,index) {
                    let form = $('#addForm');
                    _action = '/update';
                    form.find("[name='id']").val(row.id);
                    form.find("[name='pid']").val(row.pid)
                    form.find("[name='type']").val(row.type)
                    form.find("[name='name']").val(row.name)
                    form.find("[name='shiro']").val(row.shiro)
                    form.find("[name='icon']").val(row.icon)
                    form.find("[name='sorting']").val(row.sorting)
                    form.find("[name='url']").val(row.url)
                    form.find("[name='description']").val(row.description)

                    $('#addModal').modal('show');
                    form.data('bootstrapValidator').resetForm();
                    //alert(form.data('bootstrapValidator').isValid())
                },
                'click .del': function(e,value,row,index){
                    _deleteIds = [row.id];
                    $('#deleteModal').modal('show');
                },

            }
        }],
        queryParams:function(params) {
            let $array = $('#formbar').serializeArray();
            $.each($array, function(index, val) {
                if(val.value && val.value.trim())
                    params[val.name]=val.value.trim();
            });
            return params;
        }
    });
    $('#listbar').on('click', '.add', function(event) {
        event.preventDefault();
        let form = $('#addForm');
        form.find("[name='id']").val(0);
        _action = '/add';
        $('#addModal').modal('show');
    });
    $('#listbar').on('click', '.del', function(event) {
        event.preventDefault();
        _deleteIds = Frame2.bootstrap.getSelectionsAttr(table,'id');
        if (_deleteIds == null || _deleteIds.length == 0) {
            alerter.show(100,function(){},{autohide:3000,title:'提示：',content:'请选择要删除的数据！'})
        } else{
            $('#deleteModal').modal('show');
        };
    });
    // type下来菜单
    const typeSelect = $('#tablebar').find("#type");
    for(let i=0;i<convertor.type.length;i++) {
        typeSelect.append('<option value="'+i+'">'+convertor.type[i]+'</option>');
    }
    //确认删除事件
    $('#deleteModal').on('click', '.del', function(event) {
        event.preventDefault();
        console.log(_deleteIds)
        $.ajax({
            url: _DIR + '/delete',
            type: 'POST',
            dataType: 'json',
            data: {ids: _deleteIds},
            success: function(result) {
                $('#deleteModal').modal('hide');
                if (result.code == 200) {
                    alerter.show(100,function(){},{autohide:3000,content:'数据删除成功。'})
                    table.bootstrapTable('refresh');
                    loadTree(1);
                } else{
                    alerter.show(100,function(){},{autohide:5000,content:result.message})
                };
            },complete: function(){
                _deleteIds = [];
            }
        });
    });
    //新增表单验证+提交
    $('#addForm').bootstrapValidator(Frame2.bootstrap.validatorConfig({
        fields:{
            name: {
                message: '资源名不能为空',
                validators: {
                    notEmpty: {
                        message: '资源名不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 10,
                        message: '资源名长度不能小于2位或超过10位'
                    },
                }
            },
            url: {
                message: '资源Url不能为空',
                validators: {
                    stringLength: {
                        min: 3,
                        max: 100,
                        message: '资源地址长度不能小于3位或超过100位'
                    },
                }
            },
            sorting: {
                message: '请设置资源显示顺序',
                validators: {
                    notEmpty: {
                        message: '资源顺序不能为空'
                    },
                    number: {
                        min : 1,
                        max : 9999,
                        message: '资源顺序只能是1-9999'
                    }
                }
            },
        }
    })).on('success.form.bv', function(e) {
        e.preventDefault();
        let form = $(e.target);
        $.ajax({
            url: _DIR + _action,
            type: 'POST',
            dataType: 'json',
            data: form.serialize(),
            success: function(result) {
                if (result.code == 200) {
                    alerter.show(100,function(){},{autohide:3000,content:'操作成功。'})
                    $('#addModal').modal('hide');
                    table.bootstrapTable('refresh');
                    loadTree(1);
                } else{
                    alerter.show(100,function(){},{autohide:5000,content:result.message})
                };
            }
        });
        return false;
    });
    function loadTree(reload) {
        if (reload) {
            let zTree = $.fn.zTree.getZTreeObj("permissiontree");
            if (zTree.length) zTree.destroy();
        }
        $.ajax({
            url: _DIR + '/allDirTree',
            type: 'POST',
            dataType: 'json',
            data: {},
            success: function (result) {
                openTree(result.data);
                $.fn.zTree.init($("#permissiontree"), setting, result.data);
            }, complete: function () {
                let zTree = $.fn.zTree.getZTreeObj("permissiontree");
            }
        });
    }
    function openTree(tree) {
        if(tree == null) return;
        tree.open = true;
        if (tree.children.length == 0) {
            delete tree.children;
            return;
        }
        for(let i=0; i<tree.children.length; i++) {
            openTree(tree.children[i]);
        }
    }
    loadTree(0);
});
